package net.superdvach.web;

import net.superdvach.core.*;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.log4j.Logger;
import freemarker.template.*;
import com.sun.net.httpserver.*;

public class WebClient implements HttpHandler {
	public void start() throws IOException {
			Config config = Core.getConfig();
			int port = Integer.parseInt(config.getProperty("WebClientPort", "2010"));
			m_server = HttpServer.create(new InetSocketAddress(port), 10);
			m_server.createContext("/", this);
			m_server.start();
			
			m_cfg = new Configuration();
			m_cfg.setDirectoryForTemplateLoading(new File("data/templates"));
			//m_cfg.setObjectWrapper(new DefaultObjectWrapper());
			m_cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
			
			m_dataRoot = new SimpleHash();
			m_dataRoot.put("version", Core.getVersionString());
			
			m_handlers = new TreeMap<String, HttpHandler>();
			m_handlers.put("home", new HomeHandler(this));
			m_handlers.put("settings", new SettingsHandler(this));
	}
	
	public void shutdown() {
		m_server.stop(0);
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		try {
			exchange.getResponseHeaders().add("Expires",
					"Mon, 20 Dec 1998 01:00:00 GMT");
			exchange.getResponseHeaders().add("Cache-Control",
					"no-cache, must-revalidate");
			exchange.getResponseHeaders().add("Pragma", "no-cache");
			String action = getAction(exchange.getRequestURI().getQuery());
			logger.debug("Request: [" + exchange.getRequestURI().getPath() + "][" + exchange.getRequestURI().getQuery() + "]");
			if(exchange.getRequestURI().getPath().equals("/") && exchange.getRequestURI().getQuery() == null)
				action = "home";
			logger.debug("Action: " + action);
			HttpHandler handler = null;
			if(action != null)
				handler = m_handlers.get(action);
			if(handler == null) {
				File file = new File("data/webfiles" + exchange.getRequestURI().getPath());
				if (!file.exists()) {
					logger.debug("404");
					PrintWriter out = new PrintWriter(exchange.getResponseBody());
					exchange.sendResponseHeaders(404, 0);
					Template tpl = m_cfg.getTemplate("404.htpl");
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("s2ch", dataRoot());
					tpl.process(map, out);
					out.close();
				}
				else
				{
					logger.debug("200");
					FileInputStream stream = new FileInputStream(file);
					exchange.sendResponseHeaders(200, 0);
					byte[] buffer = new byte[256 * 1024];
					while(stream.available() > 0)
					{
						stream.read(buffer);
						exchange.getResponseBody().write(buffer);
					}
				}
			}
			else {
				logger.debug("Action");
				handler.handle(exchange);
			}
			logger.debug("Request done");

			exchange.close();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private String getAction(String query) {
		if(query == null)
			return null;
		String[] parameters = query.split("&");
		for(String param : parameters) {
			String[] parts = param.split("=");
			if(parts.length == 2 && parts[0].equals("action")) {
				return parts[1]; 
			}
		}
		return null;
	}
	
	Configuration templateEngine() {
		return m_cfg;
	}
	
	SimpleHash dataRoot() {
		return m_dataRoot;
	}
	
	private HttpServer m_server;
	private Configuration m_cfg;
	private Map<String, HttpHandler> m_handlers;
	private SimpleHash m_dataRoot;
	static Logger logger = Logger.getLogger(WebClient.class);
}
